<?php

namespace App\Http\Controllers\Member;

use App\Http\Controllers\Controller;
use App\Jobs\SendInvoiceEmail;
use App\Models\Log\CashLog;
use App\Models\Member\Member;
use App\Models\Service\EmailVerify;
use App\Models\User\Invoice;
use App\Models\User\Withdrawal;
use App\Traits\Upload;
use Artisan;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Mail;
use Storage;


class ManagerController extends Controller {
	use Upload;

	/*------------会员管理-------------------*/
	public function user( Request $request ) {
		if ( $request->isMethod( 'POST' ) ) {
			$value = $request->get( 'value' );
			$limit = $request->get( 'limit', 10 );
			$data  = Member::orderby( 'created_at', 'DESC' )->
			where( function ( $query ) use ( $value ) {
				$query->where( 'email', 'like', '%' . $value . '%' )
				      ->orWhere( 'qq', 'like', '%' . $value . '%' )
				      ->orWhere( 'mobile', 'like', '%' . $value . '%' )
				      ->orWhere( 'nick_name', 'like', '%' . $value . '%' )
				      ->orWhere( 'wechat', 'like', '%' . $value . '%' )
				      ->orWhere( 'id', $value );
			} )->
			where( 'status', 2 )->
			paginate( $limit );
			$count = $data->total();
			if ( $data ) {
				return response()->json( [ 'code' => 0, 'msg' => 'ok', 'count' => $count, 'data' => $data ] );
			} else {
				return $this->result_api( 200, 'list error' );
			}
		}


		return view( 'manager.manager.user-list' );
	}

	public function user_blacklist( Request $request ) {
		if ( $request->isMethod( 'POST' ) ) {
			$value = $request->get( 'value' );
			$limit = $request->get( 'limit', 10 );
			$data  = Member::orderby( 'created_at', 'DESC' )->
			where( function ( $query ) use ( $value ) {
				$query->where( 'email', 'like', '%' . $value . '%' )
				      ->orWhere( 'qq', 'like', '%' . $value . '%' )
				      ->orWhere( 'mobile', 'like', '%' . $value . '%' )
				      ->orWhere( 'nick_name', 'like', '%' . $value . '%' )
				      ->orWhere( 'wechat', 'like', '%' . $value . '%' )
				      ->orWhere( 'id', $value );
			} )->
			where( 'status', 1 )->
			paginate( $limit );
			$count = $data->total();
			if ( $data ) {
				return response()->json( [ 'code' => 0, 'msg' => 'ok', 'count' => $count, 'data' => $data ] );
			} else {
				return $this->result_api( 200, 'list error' );
			}
		}

		return view( 'manager.manager.user-blacklist' );
	}

	public function user_recharge( Request $request ) {
		if ( $request->isMethod( 'POST' ) ) {
			$validator = Validator::make(
				$request->all(),
				[
					'id'   => 'required|numeric',
					'cash' => 'required|numeric',
				], [
					'id.required'   => 'id 不能为空',
					'id.numeric'    => 'id 不正确',
					'cash.required' => '金额 不能为空',
					'cash.numeric'  => '请输入 正确的金额',
				]
			);

			if ( $validator->fails() ) {
				$error      = collect( $validator->errors()->all() );
				$returnData = array(
					'code'  => '0',
					'msg'   => '验证失败',
					'data'  => $validator->errors()->first(),
					'error' => $error->toJson(),
				);

				return response()->json( $returnData, 500 );
			}

			$id = $request->get( 'id' );
			if ( $request->get( 'cash' ) > 0 ) {
				//echo '增加 正数';
				$cash = floor( $request->get( 'cash' ) * 100 ) / 100;
			} else {
				//echo '减少 负数';
				$cash = ceil( $request->get( 'cash' ) * 100 ) / 100;
			}
			$user     = Member::where( 'id', $id )->first();
			$new_cash = $user->cash - ( $cash * - 1 );
			if ( $new_cash < 0 ) {
				return $this->result_api( 200, '余额不能小于 0' );
			}
			if ( $new_cash == $user->cash ) {
				return $this->result_api( 200, '最小单位 0.01' );
			}
			//开启事务
			DB::beginTransaction();
			try {
				//现金日志
				$cash_log_data = [
					'user_id'      => $user->id,
					'out_trade_no' => 0,
					'operator'     => '[管理员:' . auth( 'admin' )->user()->id . ']',
					'value'        => $cash,
					'before'       => $user->cash,
					'after'        => $new_cash,
					'type'         => $cash > 0 ? 0 : - 1, //'支付类型 管理员充值:0 管理员扣除:-1
					'remarks'      => '', //备注
				];

				CashLog::create( $cash_log_data );
				//扣除金币
				$user->cash = $new_cash;
				$user->save();
				//提交
				DB::commit();

				return $this->result_api( 200, 'success' );
			} catch ( Exception $e ) {
				//回滚
				DB::rollback();

				//	dd( $e );
				return $this->result_api( 200, '充值失败!' );
			}
		}
	}

	public function user_status( Request $request ) {
		$validator = Validator::make(
			$request->all(),
			[
				'id'     => 'required|numeric',
				'status' => 'required',
			], [
				'id.required'     => 'id 不能为空',
				'id.numeric'      => 'id 不正确',
				'status.required' => '状态 不能为空',
			]
		);

		if ( $validator->fails() ) {
			$error      = collect( $validator->errors()->all() );
			$returnData = array(
				'code'  => '0',
				'msg'   => '验证失败',
				'data'  => $validator->errors()->first(),
				'error' => $error->toJson(),
			);

			return response()->json( $returnData, 500 );
		}
		$member         = Member::where( 'id', $request->get( 'id' ) )->first();
		$member->status = $request->get( 'status' ) == 'false' ? 1 : 2;
		$is_save        = $member->save();
		if ( $is_save ) {
			return $this->result_api( 200, 'success' );
		} else {
			return $this->result_api( 200, '修改失败!' );
		}


	}


	/*------------资金管理-------------------*/
	public function funds_withdrawal( Request $request ) {
		if ( $request->isMethod( 'POST' ) ) {
			$status = $request->get( 'status' );
			$value  = $request->get( 'value' );
			$limit  = $request->get( 'limit', 10 );
			$data   = Withdrawal::orderby( 'created_at', 'DESC' )->
			where( function ( $query ) use ( $value ) {
				$query->where( 'name', 'like', '%' . $value . '%' )
				      ->orWhere( 'access', 'like', '%' . $value . '%' )
				      ->orWhere( 'user_id', $value );
			} )->
			where( 'status', $status == null ? '!=' : '=', $status )->
			paginate( $limit );

			$count = $data->total();
			//dd($data[0]->email->first()->email);
			if ( $data ) {
				return response()->json( [ 'code' => 0, 'msg' => 'ok', 'count' => $count, 'data' => $data ] );
			} else {
				return $this->result_api( 200, 'list error' );
			}
		}

		return view( 'manager.manager.funds_withdrawal' );
	}

	public function funds_withdrawal_status( Request $request ) {
		$validator = Validator::make(
			$request->all(),
			[
				'id'     => 'required|numeric',
				'status' => 'required|numeric',
				'value'  => 'required',
			], [
				'id.required'     => 'id 不能为空',
				'id.numeric'      => 'id 不正确',
				'status.required' => '状态 不能为空',
				'status.numeric'  => '状态 参数有误',
				'value.required'  => '内容不能为空',
			]
		);

		if ( $validator->fails() ) {
			$error      = collect( $validator->errors()->all() );
			$returnData = array(
				'code'  => '0',
				'msg'   => '验证失败',
				'data'  => $validator->errors()->first(),
				'error' => $error->toJson(),
			);

			return response()->json( $returnData, 500 );

		}
		$withdrawal         = Withdrawal::where( 'id', $request->get( 'id' ) )->first();
		$withdrawal->status = $request->get( 'status' );
		if ( $request->get( 'status' ) == 1 ) {
			//同意 写入第三方交易号
			$withdrawal->trade_no = $request->get( 'value' );

			return $this->result_api( 200, $withdrawal->save() ? 'success' : '修改失败' );
		} elseif ( $request->get( 'status' ) == 2 ) {
			//开启事务
			DB::beginTransaction();
			try {

				//驳回 写入第三方交易号
				$withdrawal->remarks = $request->get( 'value' );
				//保存状态
				$withdrawal->save();

				$member   = Member::where( 'id', $withdrawal->user_id )->first();
				$new_cash = $member->cash + $withdrawal->amount;

				//现金日志
				$cash_log_data = [
					'user_id'      => $member->id,
					'out_trade_no' => 0,
					'operator'     => '[管理员:' . auth( 'admin' )->user()->id . ']',
					'value'        => $withdrawal->amount,
					'before'       => $member->cash,
					'after'        => $new_cash,
					'type'         => 14, //'支付类型  提现驳回:14
					'remarks'      => '', //备注
				];
				CashLog::create( $cash_log_data );

				//返还cash
				$member->cash = $new_cash;
				$member->save();
				DB::commit();

				return $this->result_api( 200, 'success' );
			} catch ( Exception $exception ) {
				DB::rollBack();

				return $this->result_api( 200, '提交失败' );
			}

		}

		return $this->result_api( 200, 'status error' );
	}

	public function funds_withdrawal_value( Request $request ) {

		$validator = Validator::make(
			$request->all(),
			[
				'id'     => 'required|numeric',
				'status' => 'required|numeric',
				'value'  => 'required',
			], [
				'id.required'     => 'id 不能为空',
				'id.numeric'      => 'id 不正确',
				'status.required' => '状态 不能为空',
				'status.numeric'  => '状态 参数有误',
				'value.required'  => '内容不能为空',
			]
		);

		if ( $validator->fails() ) {
			$error      = collect( $validator->errors()->all() );
			$returnData = array(
				'code'  => '0',
				'msg'   => '验证失败',
				'data'  => $validator->errors()->first(),
				'error' => $error->toJson(),
			);

			return response()->json( $returnData, 500 );
		}
		$withdrawal = Withdrawal::where( 'id', $request->get( 'id' ) )->first();
		if ( $withdrawal->status == 1 ) {
			//同意 写入第三方交易号
			$withdrawal->trade_no = $request->get( 'value' );
		} elseif ( $withdrawal->status == 2 ) {
			//驳回 写入第三方交易号
			$withdrawal->remarks = $request->get( 'value' );
		}

		return $this->result_api( 200, $withdrawal->save() ? 'success' : '修改失败' );
	}

	public function funds_invoice( Request $request ) {
		if ( $request->isMethod( 'POST' ) ) {
			$status = $request->get( 'status' );
			$value  = $request->get( 'value' );
			$limit  = $request->get( 'limit', 10 );
			$data   = Invoice::orderby( 'created_at', 'DESC' )->
			where( function ( $query ) use ( $value ) {
				$query->where( 'invoice_title', 'like', '%' . $value . '%' )
				      ->orWhere( 'invoice_id_num', 'like', '%' . $value . '%' )
				      ->orWhere( 'user_id', $value );
			} )->
			where( 'status', $status == null ? '!=' : '=', $status )->
			paginate( $limit );

			$count = $data->total();
			if ( $data ) {
				return response()->json( [ 'code' => 0, 'msg' => 'ok', 'count' => $count, 'data' => $data ] );
			} else {
				return $this->result_api( 200, 'list error' );
			}
		}

		return view( 'manager.manager.funds_invoice' );
	}

	public function funds_invoice_save( Request $request ) {
		$validator = Validator::make(
			$request->all(),
			[
				'id'    => 'required|numeric',
				'type'  => 'required',
				'value' => 'required',
			], [
				'id.required'    => 'id 不能为空',
				'id.numeric'     => 'id 不正确',
				'type.required'  => '状态 不能为空',
				'value.required' => '内容不能为空',
			]
		);

		if ( $validator->fails() ) {
			$error      = collect( $validator->errors()->all() );
			$returnData = array(
				'code'  => '0',
				'msg'   => '验证失败',
				'data'  => $validator->errors()->first(),
				'error' => $error->toJson(),
			);

			return response()->json( $returnData, 500 );

		}
		$invoice = Invoice::where( 'id', $request->get( 'id' ) )->first();
		if ( ! $invoice ) {
			return $this->result_api( 200, '请求 不存在' );
		}
		$type = $request->get( 'type' );
		if ( $type == 'invoice_img' ) {
			$delete_path = $invoice->invoice_img;
			if ( $delete_path != '' || $delete_path != null ) {
				$delete_path = str_replace( "/storage/", "/", $delete_path );
				Storage::disk( 'public' )->delete( $delete_path );
			}
			$invoice->invoice_img = $request->get( 'value' );
		}
		if ( $type == 'status_agree' ) {
			//同意 写入发票号码
			$invoice->status         = 1;
			$invoice->invoice_number = $request->get( 'value' );
		}
		if ( $type == 'status_refuse' ) {
			//驳回 写入备注
			$invoice->status  = 2;
			$invoice->remarks = $request->get( 'value' );
		}
		if ( $type == 'result_edit' ) {
			//修改信息
			if ( $invoice->status == 1 ) {
				//修改 发票号码
				$invoice->invoice_number = $request->get( 'value' );
			} elseif ( $invoice->status == 2 ) {
				//修改 驳回信息
				$invoice->remarks = $request->get( 'value' );
			}
		}

		return $this->result_api( 200, $invoice->save() ? 'success' : '修改失败' );
	}

	public function funds_invoice_email( Request $request ) {
		$validator = Validator::make(
			$request->all(),
			[
				'invoice_id' => 'required',
			], [
				'invoice_id.required' => '发票ID不能为空',
			]
		);

		if ( $validator->fails() ) {
			$error      = collect( $validator->errors()->all() );
			$returnData = array(
				'code'  => '0',
				'msg'   => '验证失败',
				'data'  => $validator->errors()->first(),
				'error' => $error->toJson(),

			);

			return response()->json( $returnData, 500 );
		}

		$invoice    = Invoice::where( 'id', $request->get( 'invoice_id' ) )->first();

		if ( ! $invoice || $invoice->status != 1 ) {
			return $this->result_api( 400, '发票单号不存在' );
		}
		$file_path = $invoice->invoice_img;
		$exists    = Storage::disk( 'public' )->exists( str_replace( "/storage/", "/", $file_path ) );
		if ( ! $exists ) {
			return $this->result_api( 400, '发票文件不存在' );
		}

		//加入队列
        $queue =  SendInvoiceEmail::dispatch($invoice->id,$invoice->receiver_email,$file_path);

//
//		//模板发送
//		Mail::send( 'public.email.password_reset_email', [
//			'username'  => '尊敬的会员',
//			'site_name' => config( 'base.email.MAIL_FROM_NAME', config( 'app.name' ) ),
//		],
//			function ( $message ) use ( $user_email, $file_path ) {
//				$to = $user_email;
//				$message->to( $to )->subject( '电子发票' );
//				//在邮件中上传附件
//				//	$file_path='/storage/upload/invoice/FbF1d5V9QIWcNV7cObl1U9MAXNDwHXp7pA1Y2ZAq.png';
//				$attachment = public_path( $file_path );
////					$message->attach($attachment,['as'=>'invoice.jpg']);
//				$message->attach( $attachment, [ 'as' => now() . '_invoice.jpg' ] );
////					$message->attach($attachment);
//			} );

		if ( count( Mail::failures() ) < 1 ) {
			return $this->result_api( 200, 'success' );
		} else {
			return $this->result_api( 400, '发送邮件失败，请重试！' );
		}

	}

	public function funds_cash( Request $request ) {
		if ( $request->isMethod( 'POST' ) ) {
			$type  = $request->get( 'type' );
			$value = $request->get( 'value' );
			$limit = $request->get( 'limit', 10 );
			$data  = CashLog::orderby( 'created_at', 'DESC' )->
			where( function ( $query ) use ( $value ) {
				$query->where( 'user_id', $value )
				      ->orWhere( 'operator', 'like', '%' . $value . '%' );
			} )->
			where( 'type', $type == null ? '!=' : '=', $type )->
			paginate( $limit );
			$count = $data->total();

			if ( $data ) {
				return response()->json( [ 'code' => 0, 'msg' => 'ok', 'count' => $count, 'data' => $data ] );
			} else {
				return $this->result_api( 200, 'list error' );
			}
		}

		return view( 'manager.manager.funds_cash_list' );
	}


	/*------------网站设置-------------------*/
	function setting( Request $request ) {
		$type = $request->get( 'type' ) ? $request->get( 'type' ) : 'base';
		if ( $request->isMethod( 'POST' ) ) {
			$data     = config( 'base' );
			$new_data = [];
			if ( $type == 'base' ) {
				foreach ( $data['base'] as $k1 => $v1 ) {
					$new_data[] = [ 'name' => $k1, 'value' => $v1 ];
				}
			}
			if ( $type == 'withdrawal' ) {
				foreach ( $data['withdrawal'] as $k1 => $v1 ) {
					$new_data[] = [ 'name' => $k1, 'value' => $v1 ];
				}
			}
			if ( $type == 'email' ) {
				foreach ( $data['email'] as $k1 => $v1 ) {
					$new_data[] = [ 'name' => $k1, 'value' => $v1 ];
				}
			}
			if ( $type == 'alipay' ) {
				foreach ( $data['alipay'] as $k1 => $v1 ) {
					$new_data[] = [ 'name' => $k1, 'value' => $v1 ];
				}
			}

			if ( $new_data ) {
				return response()->json( [ 'code' => 0, 'msg' => 'ok', 'data' => $new_data ] );
			} else {
				return $this->result_api( 200, 'list error' );
			}
		}

		return view( 'manager.manager.setting' );

	}


	function setting_edit(
		Request $request
	) {
		$type = $request->get( 'type' );
		$data = config( 'base' );
		if ( $data[ $type ][ $request->get( 'data' )['name'] ] != '' ) {
			$data[ $type ][ $request->get( 'data' )['name'] ] =
				trim( $request->get( 'data' )['value'] );
			$is_save                                          = self::setConfig( $data );
		} else {
			return $this->result_api( 200, '参数错误' );
		}
		if ( $is_save ) {
			return $this->result_api( 200, 'success' );
		} else {
			return $this->result_api( 200, '修改失败' );
		}

	}

	private function setConfig(
		$config_data
	) {
		//config设置
		try {
			file_put_contents( config_path( 'base.php' ),
				"<?php \n return " . var_export( $config_data, true ) . ";" );
			Artisan::call( 'config:cache' );
		} catch ( Exception $e ) {
			return false;
		}

		return true;
	}

}
